﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Windsor.Configuration;

namespace NFit.Core
{
    /// <summary>
    /// Define a common locator to abstract the use of Castle Windsor
    /// </summary>
    public static class ServiceLocator
    {
        private static WindsorContainer container;

        static ServiceLocator()
        {
            Initialize();
        }

        /// <summary>
        /// Initialize the service locator
        /// </summary>
        public static void Initialize()
        {
            Initialize(null);
        }

        /// <summary>
        /// Initialize the service locator from a specific configuration file
        /// </summary>
        /// <param name="fileName"></param>
        public static void Initialize(string fileName)
        {
            IConfigurationInterpreter interpreter = GetInterpreter(fileName);
            if (interpreter == null)
                container = new WindsorContainer();
            else
                container = new WindsorContainer(interpreter);

            InitializeContainer();
        }

        private static IConfigurationInterpreter GetInterpreter(string fileName)
        {
            IConfigurationInterpreter interpreter = null;
            try
            {
                //if (!string.IsNullOrEmpty(fileName))
                //{
                //    interpreter = new XmlInterpreter(fileName);
                //}
                //else
                //{
                //    interpreter = new XmlInterpreter();
                //}
                interpreter = new XmlInterpreter();
            }
            catch (Exception)
            {
                
            }
            return interpreter;
        }

        private static void InitializeContainer()
        {
            container.Register(
                AllTypes.Pick()
                .FromAssembly(typeof(ServiceLocator).Assembly)
                .WithService.FirstInterface());
        }

        /// <summary>
        /// Resolve a type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            return container.Resolve<T>();
        }

        /// <summary>
        /// Resolve a type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Resolve<T>(string key)
        {
            return container.Resolve<T>(key);
        }
    }
}
